package com.party.web.biz.article;

import com.party.common.utils.StringUtils;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleType;
import com.party.core.model.material.MaterialMember;
import com.party.core.service.article.IArticleMemberService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.material.IMaterialMemberService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.biz.file.FileBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 文章业务接口
 * Created by wei.li
 *
 * @date 2017/3/22 0022
 * @time 19:44
 */
@Service
public class ArticleBizService {

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IMaterialMemberService materialMemberService;

    @Autowired
    private IArticleMemberService articleMemberService;

    @Autowired
    private CosBizService cosBizService;

    protected static Logger logger = LoggerFactory.getLogger(ArticleBizService.class);

    /**
     * 拼接分销连接
     *
     * @param id       活动编号
     * @param memberId 创建者
     * @return 分销连接
     */
    public String getDistributionUrl(String id, String memberId) {
        StringBuilder stringBuilder = new StringBuilder("article/article_distribution_detail.html?");
        stringBuilder.append("id=").append(id)
                .append("&parentId=").append("0")
                .append("&distributorId=").append(memberId);
        return stringBuilder.toString();
    }

    public void uploadQrCode(String memberId, String articleId) throws Exception {
        String filePath = fileBizService.getUploadCIPath(memberId, "article");

        String fileName = "detail_" + articleId;
        String content = "article/article_detail.html?id=" + articleId;
        fileBizService.uploadCloudOut(fileName, filePath, content, memberId);

        String disFileName = "dis_" + articleId;
        String disContent = getDistributionUrl(articleId, memberId);
        fileBizService.uploadCloudOut(disFileName, filePath, disContent, memberId);
    }

    /**
     * @Description:  素材管理保存
     * @Param:
     * @return:
     * @Author: Hua Qunhao
     * @Date: 2019/12/10
     */
    public void materialmgmtSave(Article article, String memberId) throws Exception{
        if (StringUtils.isNotEmpty(article.getContent())) {
            String content = StringUtils.escapeHtml4Iframe2Video(article.getContent().trim());
            article.setContent(content);
        }
        if (article.getReadNum() == null) {
            article.setReadNum(0);
        }
        if (StringUtils.isNotEmpty(article.getId())) {
            Article t = articleService.get(article.getId());
            MyBeanUtils.copyBeanNotNull2Bean(article, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
            articleService.update(t);
        } else {
            article.setCreateBy(memberId);
            article.setUpdateBy(memberId);
            article.setMemberId(memberId);
            article.setArticleType(ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
            String articleId = articleService.insert(article);
        }
        try {
            this.uploadQrCode(memberId, article.getId());
        } catch (Exception e) {
            logger.error("生成文章二维码异常", e);
        }
    }

    public void saveOrUpdateMaterialMember(String articleId, String memberIds) {
        if (StringUtils.isNotEmpty(memberIds)) {
            MaterialMember materialMember = new MaterialMember();
            materialMember.setArticleId(articleId);
            List<MaterialMember> memberList = materialMemberService.list(materialMember);
            for (MaterialMember db : memberList) {
                materialMemberService.deleteByUnique(articleId, db.getMemberId());
            }
            for (int i = 0; i < memberIds.split(",").length; i++) {
                MaterialMember insertMaterialMember = new MaterialMember();
                insertMaterialMember.setArticleId(articleId);
                insertMaterialMember.setMemberId(memberIds.split(",")[i]);
                materialMemberService.insert(insertMaterialMember);
            }
        }
    }

    /**
     * 删除文章
     *
     * @param articleId 文章编号
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteArticleBiz(String articleId) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(articleId)) {
                endResult = false;
                return endResult;
            }
            Article article = articleService.get(articleId);
            if (article == null) {
                endResult = false;
                return endResult;
            }
            memberId = article.getMemberId();
            articleMemberService.deleteByArticleId(articleId);
            articleService.delete(articleId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除文章失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "article");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, "detail_" + articleId);
                    cosBizService.deleteFile(detailPath);
                    String distributorPath = CosBizService.getDeleteQrCodePath(filePath, "dis_" + articleId);
                    cosBizService.deleteFile(distributorPath);
                } catch (Exception e) {
                    logger.error("删除文章二维码失败", e);
                }
            }
        }
        return endResult;
    }
}
